<template>
  <div class="tags-view">
    <el-scrollbar>
      <router-link
            class="tags-view-item"
            :class="isActive(tag) ? 'active' : ''"
            v-for="(tag,index) in $store.getters.tagsViewList"
            :key="tag.fullPath"
            :to="{ path: tag.fullPath }"
            @contextmenu.prevent="openMenu($event, index)"
          >
            <span>{{ tag.title }}</span>
            <svg-icon
              icon="close-tags"
              class="close-btn"
              @click.prevent.stop="onCloseClick(index)"
          />
        
        </router-link>
    </el-scrollbar>
    <context-menu
      v-show="visible"
      :style="menuStyle"
      :index="selectIndex"
    ></context-menu>
  </div>
</template>

<script setup>
import ContextMenu from './ContextMenu'
import { useRoute } from 'vue-router'
import router from '@/router'
import { ref, reactive, watch } from 'vue'
import { useStore } from 'vuex';
import { TAGS_VIEW } from '@/constant'


const route = useRoute()
const store = useStore()


//  是否被选中
const isActive = tag => {
  return tag.path === route.path
}

//  关闭 tag 的点击事件
const onCloseClick = index => {
  // 只有一个标签不能关闭
  if (store.getters.tagsViewList.length === 1) return
  // 关闭的标签是当前路由 则路由跳到列表第一个
  if(store.getters.tagsViewList[index].fullPath === route.path){
    // 点击标签是列表第一个 则跳第二个
    if (index === 0){
      router.push(store.getters.tagsViewList[1].fullPath)
    }else{
      router.push(store.getters.tagsViewList[0].fullPath)
    }
  }
  store.commit('app/removeTagsView', {
    type: 'index',
    index: index
  })
}

// contextMenu 相关
const selectIndex = ref(0)
const visible = ref(false)
const menuStyle = reactive({
  left: 0,
  top: 0
})

// 展示 menu 
const openMenu = (e, index) => {
  const { x, y } = e
  menuStyle.left = x + 'px'
  menuStyle.top = y + 'px'
  selectIndex.value = index
  visible.value = true
}

// 关闭 menu
const closeMenu = () => {
  visible.value = false
}


// 监听变化
watch(visible, val => {
  if (val) {
    document.body.addEventListener('click', closeMenu)
  } else {
    document.body.removeEventListener('click', closeMenu)
  }
})

</script>
<style lang="scss" scoped>
@import '@/styles/variables.scss';
@import '@/styles/mixin.scss';

.tags-view{
  height: 40px;
  padding: 0 5px;
  box-sizing: border-box;
  background: #fff;
  border-bottom: 1px solid #d8dce5;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 0 3px 0 rgba(0, 0, 0, 0.04);
}

.tags-view-item{
   display: inline-block;
  cursor: pointer;
  height: 32px;
  line-height: 32px;
  border: 1px solid #d8dce5;
  color: #495060;
  background: #fff;
  padding: 0 10px;
  font-size: 12px;
  margin-left: 5px;
  text-decoration: none;
  margin-top: 7px;
}
.active{
    border-bottom: none;
    border-top: 2px solid #303e4d;
    background: #F5F5F5;

}
// close 按钮
.close-btn{
  margin-left: 8px;
  font-size: 12px;

}
.close-btn:hover{
  font-size: 13px;
}

</style>